<?php
namespace app\api\controller;

use app\home\model\Article as ModelArticle;
use app\home\model\ShortLink;
use PullWord\Facade\PullWord;
use tcwei\smallTools\GetImgSrc;
use think\facade\Db;
use think\facade\Request;

class Article
{
    public function index()
    {
        $page = request()->param('page') - 1;
        $page *= 10;
        $sql = "SELECT id FROM stpc_qzz_article ORDER BY id DESC LIMIT $page, 1";
        $last_article = Db::query($sql);
        if (!count($last_article)){
            return json([
                'status'=>200,
                'articles'=>[],
                'count'=>ModelArticle::count(),
            ]);
        }
        $last_article_id = $last_article[0]['id'];

        $temp = ModelArticle::field(['id', 'title', 'summary', 'image', 'source', 'addtime', 'updatatime', 'keywords'])->where('id', '<=', $last_article_id)->order('id desc')->limit(0, 10)->select();
        $articles = [];
        foreach($temp as $a){
            $temp_a = [
                'id' => $a->id,
                'title' => $a->title,
                'summary' => $a->summary,
                'source' => $a->source,
                'image' => $a->image,
                'addtime' => $a->getData('addtime'),
                'updatatime' => $a->getData('updatatime'),
                'keywords' => $a->keywords,
            ];
            array_push($articles, $temp_a);
        }
        return json([
            'status'=>200,
            'articles'=>$articles,
            'last_id'=>$last_article_id,
            'count'=>ModelArticle::count(),
        ]);
        
    }

    public function add()
    {
        $data = Request::param();
        try {
            if($data['summary'] == ""){
                $content = strip_tags($data['content']);
                $data['summary'] = mb_substr($content, 0, 40).'...';
            }
            if ($data['image'] == ""){
                $data['image'] = GetImgSrc::src($data['content']);
            }
            if ($data['keywords'] == ""){
                $title = $data['title'];
                $result = (array)json_decode(PullWord::pull($title)->toJson()->get());
                $str = "";
                foreach($result as $i => $r){
                    $str .= $r->t;
                    if ($i != count($result) - 1){
                        $str .= ', ';
                    }
                }
                $data['keywords'] = $str;
            }
        }catch(\Exception $e){
            return json("处理信息时出错:".$e->getMessage(), 500);
        }

        try{
            $hash = md5($data['title'].microtime(true));
            $hash = substr(base64_encode($hash), 0, 6);
            $data['hash_str'] = $hash;
            $article = new ModelArticle();
            $data['addtime'] = $data['updatatime'] = date("Y:m:d H:i:s");
            $article->save($data);
            $id = $article->id ;
            $st = new ShortLink();
            $st->save([
                'c_name' => 'Pd',
                'hash_str' => $data['hash_str'],
                'p_name' => 'page',
                'p_id' => $id,
            ]);

            return json([
                'article'=>ModelArticle::field(['title', 'summary', 'image', 'source', 'addtime', 'updatatime', 'keywords'])->find($article->id),
            ]);
        }catch(\Exception $e){
            return json("添加短连接时出错:".$e->getMessage(), 500);
        }
        
       
    }

    public function edit(){
        $data = request()->param();
        $article = ModelArticle::find($data['id']);

        return json([
            'status'=>$article->save($data),
            'article'=>$article->hidden([
                'hash_str',
                'content',
            ]),
        ]);
    }

    public function del(){
        $article = ModelArticle::field(['hash_str', 'id'])->find(request()->param('id'));
        ShortLink::where('hash_str', $article->hash_str)->delete();
        return json(ModelArticle::destroy($article->id));
    }

    public function getArticle(){
        $id = request()->param('id');
        return json(ModelArticle::field(['id', 'title', 'summary', 'source', 'image', 'content', 'keywords'])->find($id));
    }
}
